import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PIL import Image
import threading
import time

class ImageConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片转JPG格式工具")
        self.root.geometry("600x400")
        self.root.resizable(True, True)
        
        # 设置中文字体支持
        self.style = ttk.Style()
        self.style.configure("TLabel", font=("SimHei", 10))
        self.style.configure("TButton", font=("SimHei", 10))
        self.style.configure("TProgressbar", thickness=20)
        
        # 变量
        self.directory = tk.StringVar()
        self.status = tk.StringVar(value="就绪")
        self.progress = tk.DoubleVar(value=0)
        self.converting = False
        self.image_extensions = ('.png', '.bmp', '.gif', '.tiff', '.webp', '.jpeg')
        
        # 创建界面
        self.create_widgets()
    
    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 目录选择
        ttk.Label(main_frame, text="目标目录:").pack(anchor=tk.W, pady=(0, 5))
        
        dir_frame = ttk.Frame(main_frame)
        dir_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Entry(dir_frame, textvariable=self.directory, width=50).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        ttk.Button(dir_frame, text="浏览...", command=self.browse_directory).pack(side=tk.RIGHT)
        
        # 转换按钮
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)
        
        self.convert_btn = ttk.Button(btn_frame, text="开始转换", command=self.start_conversion)
        self.convert_btn.pack(fill=tk.X)
        
        # 进度条
        ttk.Label(main_frame, text="转换进度:").pack(anchor=tk.W, pady=(15, 5))
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress, maximum=100)
        self.progress_bar.pack(fill=tk.X, pady=(0, 10))
        
        # 状态标签
        ttk.Label(main_frame, textvariable=self.status).pack(anchor=tk.W, pady=(15, 5))
        
        # 日志区域
        ttk.Label(main_frame, text="转换日志:").pack(anchor=tk.W, pady=(15, 5))
        
        log_frame = ttk.Frame(main_frame)
        log_frame.pack(fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(log_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.log_text = tk.Text(log_frame, height=8, wrap=tk.WORD, yscrollcommand=scrollbar.set)
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.log_text.config(state=tk.DISABLED)
        
        scrollbar.config(command=self.log_text.yview)
    
    def browse_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.directory.set(directory)
    
    def start_conversion(self):
        if self.converting:
            return
            
        dir_path = self.directory.get()
        if not dir_path or not os.path.isdir(dir_path):
            messagebox.showerror("错误", "请选择有效的目录")
            return
        
        # 查找所有图片文件
        image_files = []
        for root_dir, _, files in os.walk(dir_path):
            for file in files:
                if file.lower().endswith(self.image_extensions):
                    image_files.append(os.path.join(root_dir, file))
        
        if not image_files:
            messagebox.showinfo("信息", "未找到任何可转换的图片文件")
            return
        
        # 开始转换（在新线程中进行，避免界面冻结）
        self.converting = True
        self.convert_btn.config(text="转换中...", state=tk.DISABLED)
        self.clear_log()
        self.log(f"找到 {len(image_files)} 个图片文件，开始转换...")
        
        # 启动转换线程
        threading.Thread(target=self.convert_images, args=(image_files,), daemon=True).start()
    
    def convert_images(self, image_files):
        total = len(image_files)
        success = 0
        failed = 0
        
        for i, file_path in enumerate(image_files):
            try:
                # 构建新文件名
                dir_name, file_name = os.path.split(file_path)
                base_name = os.path.splitext(file_name)[0]
                new_file_path = os.path.join(dir_name, f"{base_name}.jpg")
                
                # 避免重复转换
                if file_path.lower() == new_file_path.lower():
                    self.log(f"跳过: {file_path} (已是JPG格式)")
                    success += 1
                    self.update_progress((i + 1) / total * 100)
                    continue
                
                # 打开并转换图片
                with Image.open(file_path) as img:
                    # 处理透明通道
                    if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
                        background = Image.new(img.mode[:-1], img.size, (255, 255, 255))
                        background.paste(img, img.split()[-1])
                        img = background
                    
                    # 保存为JPG
                    img.convert('RGB').save(new_file_path, 'JPEG', quality=95)
                
                self.log(f"转换成功: {file_path} -> {new_file_path}")
                success += 1
                
            except Exception as e:
                self.log(f"转换失败: {file_path} - 错误: {str(e)}")
                failed += 1
            
            # 更新进度
            self.update_progress((i + 1) / total * 100)
            time.sleep(0.01)  # 短暂休眠，让UI有机会更新
        
        # 转换完成
        self.status.set(f"转换完成 - 成功: {success}, 失败: {failed}")
        self.converting = False
        self.root.after(0, lambda: self.convert_btn.config(text="开始转换", state=tk.NORMAL))
        messagebox.showinfo("完成", f"转换完成\n成功: {success} 个文件\n失败: {failed} 个文件")
    
    def update_progress(self, value):
        self.progress.set(value)
        self.status.set(f"正在转换... {int(value)}%")
    
    def log(self, message):
        # 在主线程中更新UI
        self.root.after(0, lambda: self._append_log(message))
    
    def _append_log(self, message):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)
    
    def clear_log(self):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)

if __name__ == "__main__":
    # 确保中文显示正常
    root = tk.Tk()
    app = ImageConverterApp(root)
    root.mainloop()
